//
//  OrderDetailViewController.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/8/26.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh
import MJExtension

class MyOrderViewController: UIViewController {

    fileprivate lazy var orderCountData: [OrderDetailModel] = [OrderDetailModel]()
    fileprivate var paymentData: [OrderDetailModel] = [OrderDetailModel]()
    fileprivate var cancelData: [OrderDetailModel] = [OrderDetailModel]()
    
    fileprivate var canGoNext0 = true
    fileprivate var canGoNext1 = true
    fileprivate var canGoNext2 = true
    
    fileprivate var orderPage = 1
    fileprivate var paymentPage = 1
    fileprivate var cancelPage = 1
    
    fileprivate var orderResult = (order:"?orderResult=0",payment :"?orderResult=1" ,cancle : "?orderResult=2")
    
    fileprivate let userDefault = UserDefaults.standard
    fileprivate var TYPE: Int = 0
    
    fileprivate lazy var topBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: kScreenW - 60, y: kScreenH - 64 - 50 - 60, width: 40, height: 40)
        btn.setImage(UIImage(named:"huojian_03"), for: .normal)
        btn.addTarget(self, action: #selector(topBtnClick), for: .touchUpInside)
        return btn
    }()
    
    fileprivate lazy var segment: HMSegmentedControl = {
        let sgTitles = ["待支付", "已完成", "已取消"]
        let segment = HMSegmentedControl(sectionTitles: sgTitles)
        segment?.selectedSegmentIndex = 0
        segment?.isVerticalDividerEnabled = true
        segment?.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed
        segment?.backgroundColor = UIColor.white
        segment?.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown
        segment?.borderType = .customer
        segment?.customerBordrInsetBackground = UIEdgeInsetsMake(0, 5, 1, 5)
        segment?.borderColor = UIColor.gray
        segment?.borderWidth = 0.5
        segment?.selectionIndicatorColor = UIColor(r: 0, g: 184, b: 255)
        segment?.selectionIndicatorHeight = 2
        segment?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor(r:150, g: 150, b: 150), NSFontAttributeName: UIFont.systemFont(ofSize: 14*WIDTH_SCALE)]
        segment?.selectedTitleTextAttributes = [NSForegroundColorAttributeName: UIColor(r: 0, g: 184, b: 255), NSFontAttributeName: UIFont.systemFont(ofSize: 16*WIDTH_SCALE)]
        segment?.addTarget(self, action: #selector(self.segmentedControlChangedValue), for: .valueChanged)
        return segment!
    }()
    
    fileprivate lazy var scrollView: UIScrollView = {
    
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE))
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.tag = 100
        scrollView.contentSize = CGSize(width: 3*kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE)
        scrollView.backgroundColor = UIColor.randomColor()
        scrollView.delegate = self
        return scrollView
    }()
    
    fileprivate lazy var noPayTableView: UITableView = {
        let table = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE))
        table.tag = 120
        table.delegate = self
        table.dataSource = self
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = UIColor(r: 249, g: 249, b: 249)
        table.registerCell(OrderDetailCell.self)
        table.separatorStyle = .none
        return table
    }()
    
    fileprivate lazy var paymentTableView: UITableView = {
        let table = UITableView(frame: CGRect(x: kScreenW, y: 0, width: kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE))
        table.tag = 121
        table.delegate = self
        table.dataSource = self
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = UIColor(r: 249, g: 249, b: 249)
//        table.backgroundColor = UIColor.randomColor()
        table.registerCell(OrderDetailCell.self)
        table.separatorStyle = .none
        return table
    }()
    
    fileprivate lazy var cancelTableView: UITableView = {
        let table = UITableView(frame: CGRect(x: kScreenW * 2, y: 0, width: kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE))
        table.tag = 122
        table.delegate = self
        table.dataSource = self
        table.showsVerticalScrollIndicator = false
        table.backgroundColor = UIColor(r: 249, g: 249, b: 249)
//        table.backgroundColor = UIColor.randomColor()
        table.registerCell(OrderDetailCell.self)
        table.separatorStyle = .none
        return table
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "订单详情"
        view.backgroundColor = UIColor(r: 249, g: 249, b: 249)
        
        setupUI()
        
        setupHeaderRefresh()
    }

}

// MARK: - init code
extension MyOrderViewController {
    fileprivate func setupUI() {
        
        view.addSubview(segment)
        segment.snp.makeConstraints { (make) in
            make.top.equalTo(self.view)
            make.left.equalTo(self.view)
            make.size.equalTo(CGSize(width: kScreenW, height: 40*HEIGHT_SCALE))
        }
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(self.segment.snp.bottom).offset(10*HEIGHT_SCALE)
            make.left.bottom.equalTo(self.view)
            make.width.equalTo(kScreenW)
        }
        
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
        scrollView.scrollRectToVisible(CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE), animated: true)
        segment.indexChangeBlock = { (index: NSInteger) in
            self.scrollView.scrollRectToVisible(CGRect(x: kScreenW * CGFloat(index), y: 0, width: kScreenW, height: kScreenH - 64 - 50*HEIGHT_SCALE), animated: true)
        }
        
        
        scrollView.addSubview(noPayTableView)
        scrollView.addSubview(paymentTableView)
        scrollView.addSubview(cancelTableView)
        
        // 设置上下拉刷新
        setupRefresh(noPayTableView)
        setupRefresh(paymentTableView)
        setupRefresh(cancelTableView)
        
    }
    
    fileprivate func setupHeaderRefresh() {
        if userDefault.integer(forKey: "bussinessType") == 1 {
            TYPE = userDefault.integer(forKey: "bussinessType")
        }
        
        if TYPE == 1 { // 技师
            
        } else {
            
            headerRefresh(orderResult.order, refresh: false, mark: 0)
            headerRefresh(orderResult.payment, refresh: false, mark: 1)
            headerRefresh(orderResult.cancle, refresh: false, mark: 2)
            
        }
    }
    
    // 设置上/下拉刷新
    fileprivate func setupRefresh(_ tableView: UITableView) {
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header.setRefreshingTarget(self, refreshingAction: #selector(helpHeaderRefresh))
        tableView.mj_footer = MJRefreshAutoNormalFooter()
//        tableView.mj_footer.isHidden = true
        tableView.mj_footer.setRefreshingTarget(self, refreshingAction: #selector(helpFooterRefresh))
        tableView.mj_footer.isAutomaticallyHidden = true
    }
    
    @objc fileprivate func helpHeaderRefresh() {
        
        if noPayTableView.mj_header.isRefreshing() {
            headerRefresh(orderResult.order, refresh: true, mark: 0)
        }
        
        if paymentTableView.mj_header.isRefreshing() {
            headerRefresh(orderResult.payment, refresh: true, mark: 1)
        }
        
        if cancelTableView.mj_header.isRefreshing() {
            headerRefresh(orderResult.cancle, refresh: true, mark: 2)
        }
    }
    
    @objc fileprivate func helpFooterRefresh() {
        
        if noPayTableView.mj_footer.isRefreshing() {
            if canGoNext0 == true {
                orderPage += 1
                footerRefresh(orderResult.order, mark: 0, page: orderPage)
            } else {
                noPayTableView.mj_footer.endRefreshingWithNoMoreData()
            }
        }
        
        if paymentTableView.mj_footer.isRefreshing() {
            if canGoNext1 == true {
                paymentPage += 1
                footerRefresh(orderResult.payment, mark: 1, page: paymentPage)
            } else {
                paymentTableView.mj_footer.endRefreshingWithNoMoreData()
            }
        }
        
        if cancelTableView.mj_footer.isRefreshing() {
            if canGoNext2 == true {
                cancelPage += 1
                footerRefresh(orderResult.cancle, mark: 2, page: cancelPage)
            } else {
                cancelTableView.mj_footer.endRefreshingWithNoMoreData()
            }
        }
    }
    
    fileprivate func setupNoOrderMessageView() {
        
        let imageView = UIImageView(imageName: "noOrder")
        imageView.tag = 1000
        imageView.contentMode = .scaleAspectFill
        view.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(self.segment.snp.bottom)
        }
        
    }
    
    fileprivate func removeNoOrderMessageView() {
        let imageView = view.viewWithTag(1000)
        imageView?.removeFromSuperview()
    }
    
    fileprivate func dealNoMessage(_ dataArr: [OrderDetailModel]) {
        if dataArr.count == 0 {
            self.setupNoOrderMessageView()
        } else {
            self.removeNoOrderMessageView()
        }

    }
}

// MARK: - data
extension MyOrderViewController {
    
    fileprivate func headerRefresh(_ orderResult: String, refresh: Bool, mark: Int) {
        
        showLoading()
        let url = Base_url + ((TYPE == 1) ? getHomeTec : STORE_DETAILS_API)
        
        NetworkTools.shareInstance.requestData(url + orderResult, .get, [:]) { (result, isSuccess) in
            
            self.hideLoading()
            switch isSuccess {
                case true:

                let json = JSON(result)
//                DZYLog(result)
//               DZYLog(json)

                if refresh {
                    
                    switch mark {
                    case 0:
                        
                        if self.TYPE == 1 {
                        
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            self.orderCountData = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr).copy() as! [OrderDetailModel]
                            self.canGoNext0 = json["isCanGoNext"].boolValue
                            self.noPayTableView.reloadData()
                            self.orderPage = 1
                            self.noPayTableView.mj_header.endRefreshing()
                            if self.canGoNext0 == false {
                                self.noPayTableView.mj_footer.endRefreshingWithNoMoreData()
                            }
                            self.dealNoMessage(self.orderCountData)
                        }
                    case 1:
                        
                        if self.TYPE == 1 {
                            
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            self.paymentData = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr).copy() as! [OrderDetailModel]
                            self.canGoNext1 = json["isCanGoNext"].boolValue
                            self.paymentTableView.reloadData()
                            self.paymentPage = 1
                            self.paymentTableView.mj_header.endRefreshing()
                            if self.canGoNext1 == false {
                                self.paymentTableView.mj_footer.endRefreshingWithNoMoreData()
                            }
                            self.dealNoMessage(self.paymentData)
                        }
                    case 2:
                        
                        if self.TYPE == 1 {
                            
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            self.cancelData = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr).copy() as! [OrderDetailModel]
                            self.canGoNext2 = json["isCanGoNext"].boolValue
                            self.cancelTableView.reloadData()
                            self.cancelPage = 1
                            self.cancelTableView.mj_header.endRefreshing()
                            if self.canGoNext2 == false {
                                self.cancelTableView.mj_footer.endRefreshingWithNoMoreData()
                            }
                           self.dealNoMessage(self.cancelData)
                        }
                    default:
                        DZYLog("参数传入错误")
                    }
                    
                } else {
                    
                    switch mark {
                    case 0:
                        
                        if self.TYPE == 1 {
                            
                        } else {

                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            self.orderCountData = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr).copy() as! [OrderDetailModel]

                            self.canGoNext0 = json["isCanGoNext"].boolValue

                            self.noPayTableView.reloadData()
                            self.noPayTableView.mj_header.endRefreshing()
                            if self.orderCountData.count < 10 && self.canGoNext0 == false {
                                self.noPayTableView.mj_footer.endRefreshingWithNoMoreData()
                            }
                            self.dealNoMessage(self.orderCountData)
                        }
                    case 1:
                        
                        if self.TYPE == 1 {
                            
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            self.paymentData = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr).copy() as! [OrderDetailModel]

                            self.canGoNext1 = json["isCanGoNext"].boolValue

                            self.paymentTableView.reloadData()
                            self.paymentTableView.mj_header.endRefreshing()
                            if self.paymentData.count < 10 && self.canGoNext1 == false {
                                self.paymentTableView.mj_footer.endRefreshingWithNoMoreData()
                            }
                            self.dealNoMessage(self.paymentData)
                        }

                    case 2:
                        
                        if self.TYPE == 1 {
                            
                        } else {

                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            self.cancelData = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr).copy() as! [OrderDetailModel]
                            self.canGoNext2 = json["isCanGoNext"].boolValue

                            self.cancelTableView.reloadData()
                            self.cancelTableView.mj_header.endRefreshing()
                            if self.cancelData.count < 10 && self.canGoNext2 == false {
                                self.cancelTableView.mj_footer.endRefreshingWithNoMoreData()
                            }
                            self.dealNoMessage(self.cancelData)
                        }
                    default:
                        DZYLog("参数传入错误")
                    }

                }
                
                case false:
                    self.showHUD(.failure, text: "无法连接服务器")
                    self.noPayTableView.mj_header.endRefreshing()
                    self.paymentTableView.mj_header.endRefreshing()
                    self.cancelTableView.mj_header.endRefreshing()
            }
            
        }
        
    }
    
    fileprivate func footerRefresh(_ orderResult: String, mark: Int, page: Int) {
        
        let url = Base_url + ((TYPE == 1) ? getHomeTec : STORE_DETAILS_API) + orderResult + "&page=" + String(page)
        NetworkTools.shareInstance.requestData(url, .get, [:]) { (result, isSuccess) in
            
            switch isSuccess {
                
            case true:
                
                let json = JSON(result)
                
                switch mark {
                    case 0:
                        if self.TYPE == 1 {
                    
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            
                            let arr: [OrderDetailModel] = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr) as! [OrderDetailModel]
                            self.orderCountData += arr
                            self.canGoNext0 = json["isCanGoNext"].boolValue
                            self.noPayTableView.reloadData()
                            self.noPayTableView.mj_footer.endRefreshing()

                    }
                    case 1:
                        if self.TYPE == 1 {
                            
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            
                            let arr: [OrderDetailModel] = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr) as! [OrderDetailModel]
                            self.paymentData += arr
                            self.canGoNext1 = json["isCanGoNext"].boolValue
                            self.paymentTableView.reloadData()
                            self.paymentTableView.mj_footer.endRefreshing()
                    }

                    case 2:
                        if self.TYPE == 1 {
                            
                        } else {
                            guard let dictArr = json["orderDetailes"].arrayObject else { return }
                            
                            let arr: [OrderDetailModel] = OrderDetailModel.mj_objectArray(withKeyValuesArray: dictArr) as! [OrderDetailModel]
                            self.cancelData += arr
                            self.canGoNext2 = json["isCanGoNext"].boolValue
                            self.cancelTableView.reloadData()
                            self.cancelTableView.mj_footer.endRefreshing()
                    }

                default :
                    break
                }
 
            case false:
                self.showHUD(.failure, text: "无法连接服务器")
                self.noPayTableView.mj_footer.endRefreshing()
                self.paymentTableView.mj_footer.endRefreshing()
                self.cancelTableView.mj_footer.endRefreshing()
            }
        }
    }
}

// MARK: - event
extension MyOrderViewController {
    @objc fileprivate func segmentedControlChangedValue(_ segment: HMSegmentedControl) {
        topBtn.removeFromSuperview()
    }
    
    @objc fileprivate func topBtnClick() {
        
        let pageW: CGFloat = scrollView.width
        let currentPage = UInt(scrollView.contentOffset.x/pageW)
        let offsetY1 = noPayTableView.contentOffset.y
        let offsetY2 = paymentTableView.contentOffset.y
        let offsetY3 = cancelTableView.contentOffset.y
        
        if currentPage == 0 && offsetY1 >= 500 {
            noPayTableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 + 141*HEIGHT_SCALE), animated: true)
        }
        
        if currentPage == 1 && offsetY2 >= 500 {
            paymentTableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 + 141*HEIGHT_SCALE), animated: true)
        }
        if currentPage == 2 && offsetY3 >= 500 {
            cancelTableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 64 + 141*HEIGHT_SCALE), animated: true)
        }
    }
    
}


// MARK: - UITableViewDelegate / UITableViewDataSource
extension MyOrderViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch tableView.tag {
        case 120:
            
            let cellCount = orderCountData.count
            return cellCount
        case 121:
            
            let cellCount = paymentData.count
            return cellCount
        case 122:
            
            let cellCount = cancelData.count
            return cellCount
            
        default:
            DZYLog(tableView)
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(indexPath: indexPath) as OrderDetailCell
        switch tableView.tag {
        case 120:
            cell.orderDetailModel = self.orderCountData[indexPath.row]
        case 121:
            cell.orderDetailModel = self.paymentData[indexPath.row]
        case 122:
            cell.orderDetailModel = self.cancelData[indexPath.row]
        default:
            break
        }
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        DZYLog("点击了cell")
        
        let orderVc = OrderDetailViewController()
        
        var orderId: String?
        switch tableView.tag {
        case 120:
            orderId = orderCountData[indexPath.row].srv_order_id
        case 121:
            orderId = paymentData[indexPath.row].srv_order_id
        case 122:
            orderId = cancelData[indexPath.row].srv_order_id
        default:
            DZYLog("错误点击")
        }
        
        orderVc.srv_order_id = orderId
        orderVc.cancelOrderBlock = { (orderID) in
            self.setupHeaderRefresh()
        }
        
        navigationController?.pushViewController(orderVc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100 * HEIGHT_SCALE
    }
    
}

// MARK: - UIScrollViewDelegate
extension MyOrderViewController : UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.tag == 120 || scrollView.tag == 121 || scrollView.tag == 122 {
            let offsetY = scrollView.contentOffset.y
            if offsetY > 500 {
                view.addSubview(topBtn)
            } else {
                topBtn.removeFromSuperview()
            }
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if scrollView.tag == 100 {
            topBtn.removeFromSuperview()
            let pageWidth: CGFloat = scrollView.width
            let currentPage: UInt = UInt(scrollView.contentOffset.x / pageWidth)
            segment.setSelectedSegmentIndex(currentPage, animated: true)
        }
    }
    
}
